package com.woniuxy.ssm.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * @program: JavaEE-EFD
 * @description:
 * @author: fengjd
 * @create: 2022-07-28 20:19
 **/

@Configuration //向spring申明这是一个配置类
@EnableTransactionManagement //向spring说明开启 事务注解
@MapperScan(basePackages = "com.woniuxy.ssm.mapper") // 告诉spring去什么路径下查找 mapper类, mapper类需要使用 @mapepr注解申明
@PropertySource("classpath:jdbc.properties") // 告诉spring去哪里找配置文件
public class App {

    @Value("${jdbc.driver}")
    private String driver;

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.username}")
    private String userName;

    @Value("${jdbc.password}")
    private String password;

    @Bean  // 将下面的方法注入为bean,有spring管理
    public static PropertySourcesPlaceholderConfigurer placeholderConfigurer(){
        return new PropertySourcesPlaceholderConfigurer();
    }

    @Bean
    public DataSource dataSource(){
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(userName);
        dataSource.setPassword(password);
        return dataSource;
    }

    /*可以看出 springmvc 可以将xml中配置的东西移动到了 类中*/
    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception{
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());
//        设置类型别名
        sqlSessionFactoryBean.setTypeAliasesPackage("com.woniuxy.ssm.entity");
        sqlSessionFactoryBean.setMapperLocations( new PathMatchingResourcePatternResolver().getResources("classpath*:mappings/*.xml") );
        return sqlSessionFactoryBean.getObject();
    }
}
